package cn.edu.neusoft.service;


import cn.edu.neusoft.config.PlatformConfig;
import cn.edu.neusoft.model.impl.CarIOImpl;
import cn.edu.neusoft.model.impl.CarInfoImpl;
import cn.edu.neusoft.model.impl.CarPeccancyImpl;
import cn.edu.neusoft.model.impl.PeoleInfoImpl;
import cn.edu.neusoft.service.event.SubscribeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.TimeZone;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Autowired
    private CarInfoImpl carInfo;

    private static int executionCount = 0;

    @Autowired
    private PeoleInfoImpl peoleInfo;
    //@Autowired
    //private SubscribeHandler subscribeHandler;

    @Autowired
    private CarIOImpl carIO;

    @Autowired
    private CarPeccancyImpl carPeccancy;

    @Autowired
    private PlatformConfig platformConfig;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private final ScheduledExecutorService schedulerPec = Executors.newScheduledThreadPool(1);

    private final ScheduledExecutorService schedulerGoast = Executors.newScheduledThreadPool(1);
    
    @Override
    public void run( ApplicationArguments args) throws Exception {
        // 这里是您的初始化逻辑
        System.out.println("应用已经启动！");
        
        carIO.clear();
        carIO.getCarIOByTime("2025-10-20 00:00:00");

        carPeccancy.clear();
        carPeccancy.getCarPeccancyByTime(0);

        int duration = Integer.parseInt(platformConfig.getDuration());
        scheduler.scheduleAtFixedRate(() -> carIO.getCarIOByTime(null), 0, duration, TimeUnit.SECONDS);

        int duration2 = Integer.parseInt(platformConfig.getPeccancyDuration());
        schedulerPec.scheduleAtFixedRate(() -> carPeccancy.getCarPeccancyByTime(-1), 0, duration2, TimeUnit.SECONDS);

        carInfo.restoreAllCars();
        peoleInfo.restoreAllPeoples();

        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        // 设置目标时间为今天的半夜12点
        Calendar midnight = (Calendar) now.clone();
        midnight.set(Calendar.HOUR_OF_DAY, 0);
        midnight.set(Calendar.MINUTE, 0);
        midnight.set(Calendar.SECOND, 0);
        midnight.set(Calendar.MILLISECOND, 0);

        // 如果当前时间已经过了半夜12点，则目标时间设为明天的半夜12点
        if (now.after(midnight)) {
            midnight.add(Calendar.DAY_OF_MONTH, 1);
        }
        // 计算延迟时间（毫秒）
        long delay = midnight.getTimeInMillis() - now.getTimeInMillis();
        // 安排任务在延迟时间后执行
        schedulerGoast.schedule(new Runnable() {
            @Override
            public void run() {
                if (++executionCount % 5 == 0) {
                    System.out.println("Task executed at midnight!");
                    carInfo.restoreAllCars();
                    peoleInfo.restoreAllPeoples();
                }

                //每5天清空一次
//                if (++executionCount % 5 == 0) {
//                    carIO.clear();
//                    carIO.getCarIOByTime("2024-01-01 00:00:00");
//                }
//
//                //每10天清空一次
//                if (++executionCount % 10 == 0) {
//                    carPeccancy.clear();
//                    carPeccancy.getCarPeccancyByTime(0);
//                }
            }
        }, delay, TimeUnit.MILLISECONDS);

        /* 订阅不好用
        //订阅预警
        subscribeHandler.subscribeAlarmEvent();
        //订阅business
        subscribeHandler.subscribeBusinessEvent();
        */
    }

    public void stop() {
        int i = Integer.parseInt(platformConfig.getDuration());
        int j = Integer.parseInt(platformConfig.getPeccancyDuration());
        scheduler.shutdown();
        schedulerPec.shutdown();
        try {
            if (!scheduler.awaitTermination(i, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
        } catch (InterruptedException ex) {
            scheduler.shutdownNow();
            Thread.currentThread().interrupt();
        }

        try {
            if (!schedulerPec.awaitTermination(j, TimeUnit.SECONDS)) {
                schedulerPec.shutdownNow();
            }
        } catch (InterruptedException ex) {
            schedulerPec.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}